﻿using System;
using System.Linq;
using System.Web;
using Portal.Data.Entity;

namespace Portal.Data.Crawler
{
    public class ComicVn
    {
        #region ctor
        private static readonly HtmlParser _parser = new HtmlParser();
        private static class Singleton
        {
            public static readonly ComicVn Instance = new ComicVn();
        }
        public static ComicVn Instance
        {
            get
            {
                return Singleton.Instance;
            }
        }
        #endregion

        #region Config

        private const string DomainLink = "http://comicvn.net";
        const string OpenBookInfo = "<div class=\"box_con";
        const string CloseBookInfo = "</div>";

        const string OpenChapItem = "<div class=\"table_line";
        const string CloseChapItem = "</div>";

        #endregion

        /// <summary>
        /// Lấy các Chap mới
        /// </summary>
        public int GetNewChaps(Book b, out string errorMessage)
        {
            int newcount = 0;
            var sources = Common.GetHtmlSources(b.CrawlUrl);
            if (sources.Length > 0)
            {
                sources = _parser.Replace(sources, HtmlParser.Patterns.BREAK, " ");
                var ss = _parser.GetContentInNode(sources, OpenBookInfo, CloseBookInfo);
                if (ss.Count > 0)
                {
                    var s = ss[0];
                    try
                    {
                        var ccl = new CommonCrawler();

                        //get list chapter
                        var allExisted = Content.FindByBook(b.ID).Select(x => x.CrawlUrl).ToList();

                        var blocklistchap = _parser.GetContentInNode(s, OpenChapItem, CloseChapItem);
                        if (blocklistchap.Count > 0)
                        {
                            int totalFromSource = blocklistchap.Count;
                            if (totalFromSource > allExisted.Count)
                            {
                                var newLastChapId = 0;
                                var idx = 1;
                                //(index =0 la chuong moi nhat)
                                while (idx <= totalFromSource)
                                {
                                    var text = HttpUtility.HtmlDecode(blocklistchap[totalFromSource - idx]);
                                    var chap = new Content { Book_ID = b.ID, Chapter = allExisted.Count + 1, SafeNameBook = b.SafeName };
                                    var tagAs = _parser.GetBetweenTag(text, "a");
                                    if (tagAs.Count > 0)
                                    {
                                        var urls = _parser.GetProperty(tagAs[0].Value, "href");
                                        if (urls.Count > 0)
                                        {
                                            var crawlUrl = urls[0].Groups[4].Value.Trim();
                                            chap.CrawlUrl = Common.FillAbsoluteLink(DomainLink, crawlUrl);
                                        }
                                        chap.Title = HttpUtility.HtmlDecode(_parser.RemoveAllTag(tagAs[0].Value).Trim());
                                    }
                                    if (!allExisted.Contains(chap.CrawlUrl))
                                    {
                                        allExisted.Add(chap.CrawlUrl);//add into existed
                                        chap.BodyTemp = ccl.GetChapBody(chap.CrawlUrl, out errorMessage);
                                        chap.Broken = chap.BodyTemp.Length == 0;
                                        chap.Save();
                                        newLastChapId = chap.Content_ID;

                                        newcount++;
                                    }

                                    //vẫn tiếp tục tăng số chương, để bỏ qua các chap "ngoại truyện"
                                    idx++;
                                }
                                if (newLastChapId > 0)
                                    b.ChangeLastChap(newLastChapId, allExisted.Count);
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        errorMessage = ex.Message;
                        return newcount;
                    }
                }
            }
            errorMessage = "";
            return newcount;
        }

    }
}

